package com.inspur.login;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(urlPatterns = "/LoginServlet")
public class Login extends HttpServlet {
    // 使用一个静态Map来存储用户名
    private static final Map<String, String> userMap = new HashMap<>();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 验证用户名是否为空
        if (username == null || username.trim().isEmpty()) {
            req.setAttribute("message", "用户名为空");
            req.getRequestDispatcher("pages/result.jsp").forward(req, resp);
            return;
        }

        // 验证密码是否为空或长度小于6
        if (password == null || password.length() < 6) {
            req.setAttribute("message", "密码为空或者密码少于6位数");
            req.getRequestDispatcher("pages/result.jsp").forward(req, resp);
            return;
        }

        // 检查用户名是否已存在
        if (userMap.containsKey(username)) {
            req.setAttribute("message", "用户名已存在");
            req.getRequestDispatcher("pages/result.jsp").forward(req, resp);
            return;
        }

        // 如果所有验证都通过，将用户名和密码存储到Map中
        userMap.put(username, password);
        req.setAttribute("message", "注册成功");
        req.getRequestDispatcher("pages/result.jsp").forward(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
